package com.genshang.restaurant.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.genshang.restaurant.entity.Accumulatelisttable;
import com.genshang.restaurant.entity.Customerlist;
import com.genshang.restaurant.mapper.AccumulatelisttableMapper;
import com.genshang.restaurant.result.CommonEnum;
import com.genshang.restaurant.result.ResultBody;
import com.genshang.restaurant.service.IAccumulatelisttableService;
import com.genshang.restaurant.service.ICouponlistService;
import com.genshang.restaurant.service.ICustomerlistService;
import com.genshang.restaurant.util.youzan.YouZanUtil;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.YouzanCrmCustomerPointsGetResult;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.YouzanUserOpenidGetbyopenidResult;
import com.youzan.cloud.open.sdk.gen.v1_0_0.model.YouzanUsersAccountCheckResult;
import com.youzan.cloud.open.sdk.gen.v3_0_1.model.YouzanUserBasicGetResult;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanCrmCustomerPointsDecreaseResult;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanCrmCustomerPointsIncreaseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Alex
 * @since 2020-09-25
 */
@Service
public class AccumulatelisttableServiceImpl extends ServiceImpl<AccumulatelisttableMapper, Accumulatelisttable> implements IAccumulatelisttableService {

    @Autowired
    private ICustomerlistService customerlistService;

    @Autowired
    private ICouponlistService couponlistService;

    @Override
    public ResultBody getYouZanAccumulate(String phone) {
        ResultBody resultBody = checkYouZanAccount(phone);
        if (resultBody.getCode() != CommonEnum.SUCCESS.getResultCode()) {
            return resultBody;
        }
        YouzanUserBasicGetResult.YouzanUserBasicGetResultData youzanUserBasicGetResultData = (YouzanUserBasicGetResult.YouzanUserBasicGetResultData) resultBody.getData();
        String yzOpenId = youzanUserBasicGetResultData.getYzOpenId();
        if (null == yzOpenId) {
            return ResultBody.error("未找到用户有赞信息");
        }
        YouzanCrmCustomerPointsGetResult youzanCrmCustomerPointsGetResult =
                YouZanUtil.getPointByYzOpenId(yzOpenId);
        if (null == youzanCrmCustomerPointsGetResult || null == youzanCrmCustomerPointsGetResult.getData()) {
            return ResultBody.error("未找到用户有赞积分信息");
        }
        YouzanCrmCustomerPointsGetResult.YouzanCrmCustomerPointsGetResultData youzanCrmCustomerPointsGetResultData =
                youzanCrmCustomerPointsGetResult.getData();
        Long point = youzanCrmCustomerPointsGetResultData.getPoint();
        return ResultBody.success(point);
    }

    @Override
    public ResultBody updateYouZanAccumulate(String phone, String youZanAccumulate, String operateType) {
        ResultBody resultBody = checkYouZanAccount(phone);
        if (resultBody.getCode() != CommonEnum.SUCCESS.getResultCode()) {
            return resultBody;
        }
        YouzanUserBasicGetResult.YouzanUserBasicGetResultData youzanUserBasicGetResultData = (YouzanUserBasicGetResult.YouzanUserBasicGetResultData) resultBody.getData();
        String yzOpenId = youzanUserBasicGetResultData.getYzOpenId();
        switch (operateType) {
            // 减少积分
            case "0":
                YouzanCrmCustomerPointsDecreaseResult decreaseResult = YouZanUtil.decreasePoint(yzOpenId, "消费减积分", Integer.valueOf(youZanAccumulate));
                if (null == decreaseResult || decreaseResult.getCode() != 200) {
                    return ResultBody.error("减积分失败");
                }
                return ResultBody.success("减积分成功");
            // 增加积分
            case "1":
                YouzanCrmCustomerPointsIncreaseResult youzanCrmCustomerPointsIncreaseResult = YouZanUtil.increasePoint(yzOpenId, "增加积分", Integer.valueOf(youZanAccumulate));
                if (null == youzanCrmCustomerPointsIncreaseResult || youzanCrmCustomerPointsIncreaseResult.getCode() != 200) {
                    return ResultBody.error("增加积分失败");
                }
                return ResultBody.success("增加积分成功");
            // 不知所措
            default:
                return ResultBody.error("参数错误，请检查");
        }
    }

    private ResultBody checkYouZanAccount(String phone) {
        Customerlist customerlist = customerlistService.getCustomerByPhone(phone);
        if (null == customerlist) {
            return ResultBody.error("未找到该用户");
        }
        if (StringUtils.isBlank(phone)) {
            ResultBody.error("未绑定手机号,无法查询");
        }
        YouzanUsersAccountCheckResult youzanUsersAccountCheckResult = YouZanUtil.checkUser(phone);
        if (null == youzanUsersAccountCheckResult || null == youzanUsersAccountCheckResult.getData() ||
                !youzanUsersAccountCheckResult.getData()) {
            return ResultBody.error("该手机号未绑定有赞账号");
        }

        YouzanUserOpenidGetbyopenidResult youzanUserOpenidGetbyopenidResult = YouZanUtil.getYouzanOpenid(phone);
        if (null == youzanUserOpenidGetbyopenidResult) {
            return ResultBody.error("该Openid未绑定有赞账号");
        }

        YouzanUserBasicGetResult youzanUserBasicGetResult = YouZanUtil.getUserInfoByPhone(phone, youzanUserOpenidGetbyopenidResult.getData().getYzOpenId());
        if (null == youzanUserBasicGetResult || !youzanUserBasicGetResult.getSuccess() || null == youzanUserBasicGetResult.getData()) {
            return ResultBody.error("未找到用户有赞信息");
        }
        YouzanUserBasicGetResult.YouzanUserBasicGetResultData youzanUserBasicGetResultData = youzanUserBasicGetResult.getData();
        String yzOpenId = youzanUserBasicGetResultData.getYzOpenId();
        if (null == yzOpenId) {
            return ResultBody.error("未找到用户有赞信息");
        }
        return ResultBody.success(youzanUserBasicGetResult.getData());
    }

    @Override
    public ResultBody exchange(String shopId, String accumulate, String openId, String goodsId) {
        Map<String, Object> resultMap = new HashMap<>();

        Integer accumulateInteger = Integer.valueOf(accumulate);
        // 1.查询用户小程序平台所剩积分
        Customerlist customerlist = customerlistService.getCustomerByPhone(openId);
        if (null == customerlist) {
            return ResultBody.error("未找到该用户");
        }
        String usablescores = customerlist.getUsablescores();
        Integer usableScore = 0;
        if (StringUtils.isNotBlank(usablescores)) {
            usableScore = Integer.valueOf(usablescores);
        }
        if (usableScore > accumulateInteger) {
            resultMap.put("needYouZan", false);
            resultMap.put("message", "不需要有攒积分");
            return ResultBody.success(resultMap);
        }
        Integer youzanPoint;
        ResultBody youZanResultBody = getYouZanAccumulate(openId);
        if (youZanResultBody.getCode() != "200") {
            return ResultBody.error("1.积分不足");
        }
        // 有赞积分要转换才能直接兑换
        youzanPoint = Integer.valueOf(youZanResultBody.getData().toString());
        Integer x = accumulateInteger - usableScore;
        Integer usableYouZanPoint = getUseAbleYouZanPoint(shopId, youzanPoint);
        if (x > usableYouZanPoint) {
            return ResultBody.error("1.积分不足");
        }

        //获取要补充的积分
        Integer needSavePoint = accumulateInteger - usableScore;
        // 减去有赞积分
        Integer youzanNeedSavePoint = getNeedSavePoint(shopId, needSavePoint);
        ResultBody resultBody = updateYouZanAccumulate(openId, youzanNeedSavePoint.toString(), "0");

        if (resultBody.getCode() != "200") {
            return resultBody;
        }

        // 增加积分
        String accumulateId = "ababaaaabXi: com.restaurant.application.accumulate.Accumulate";
        Accumulatelisttable accumulatelisttable = new Accumulatelisttable();
        accumulatelisttable.setAccumulate(accumulateId);
        accumulatelisttable.setCustomername(customerlist.getNickname());
        accumulatelisttable.setCreatetime(System.currentTimeMillis());

        accumulatelisttable.setPoints(Long.valueOf(needSavePoint));
        accumulatelisttable.setType("增加补充积分");
        accumulatelisttable.setDetail("ababaaaabYf: com.restaurant.application.coupon.Coupon");
        accumulatelisttable.setAction("兑换商品");
        accumulatelisttable.setCustomerid(customerlist.getNumber());
        Integer currentPoint = usableScore + needSavePoint;
        accumulatelisttable.setCurrentpoint(Long.valueOf(currentPoint));
        accumulatelisttable.setPhone(customerlist.getPhone());
        accumulatelisttable.setCustomeruid(customerlist.getCustomeruid());

        // 新增积分记录表
        this.save(accumulatelisttable);
        resultMap.put("needYouZan", true);
        resultMap.put("message", "要有攒积分");
        return ResultBody.success(resultMap);
    }

//        // 若有可用积分，则操作用户和积分记录表
//        Integer updateScores = 0;
//        if (usableScore >= accumulateInteger) {
//            // 2. 若平台可用积分大于所需积分，相减
//            updateScores = usableScore - accumulateInteger;
//        }
//        customerlist.setUsablescores(updateScores.toString());
//        // 更新用户表
//        customerlistService.updateById(customerlist);
//        // 增加积分记录表
//        String accumulateId = "ababaaaabXi: com.restaurant.application.accumulate.Accumulate";
//        Accumulatelisttable accumulatelisttable = new Accumulatelisttable();
//        accumulatelisttable.setAccumulate(accumulateId);
//        accumulatelisttable.setCustomername(customerlist.getNickname());
//        accumulatelisttable.setCreatetime(System.currentTimeMillis());
//        Integer points;
//        if (usableScore >= accumulateInteger) {
//            points = accumulateInteger;
//        } else {
//            points = usableScore;
//        }
//        accumulatelisttable.setPoints(Long.valueOf(points));
//        accumulatelisttable.setType("兑换减少");
//        accumulatelisttable.setDetail("ababaaaabYf: com.restaurant.application.coupon.Coupon");
//        accumulatelisttable.setAction("兑换商品");
//        accumulatelisttable.setCustomerid(customerlist.getNumber());
//        accumulatelisttable.setCurrentpoint(Long.valueOf(updateScores));
//        accumulatelisttable.setPhone(customerlist.getPhone());
//        accumulatelisttable.setCustomeruid(customerlist.getCustomeruid());
//
//        // 新增积分记录表
//        this.save(accumulatelisttable);
//        if (usableScore >= accumulateInteger) {
//            // 若所需积分小于用户积分，则返回
//            return ResultBody.success();
//        }
//        // 需要有赞积分才能满足，第一步先将有赞积分减去
//        Integer needSavePoint = accumulateInteger - usableScore;
//        needSavePoint = getNeedSavePoint(shopId, needSavePoint);

//
//        // 4.
//


    private Integer getUseAbleYouZanPoint(String shopId, Integer youZanPoint) {
        if ("01".equals(shopId)) {
            return Integer.valueOf(youZanPoint / 10);
        }
        return Integer.valueOf(youZanPoint / 20);
    }

    private Integer getNeedSavePoint(String shopId, Integer youZanPoint) {
        if ("01".equals(shopId)) {
            return Integer.valueOf(youZanPoint * 10);
        }
        return Integer.valueOf(youZanPoint * 20);
    }
}
